package system;

import com.mysql.jdbc.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;

/**
 *
 * @author Rezan Achmad
 */
public abstract class Model {

    private HashMap<String, String> errors;
    public HashMap<String, String> attributesLabel;
    public static HttpServletRequest request;
    public String message;

    public Model() {
        errors = new HashMap<String, String>();
        message = "";
        initAttributesLabel();
    }

    public Statement getStatement() {
        return DbConnection.getStatement();
    }

    public abstract boolean add();

    public abstract void setAttributes(ResultSet rs) throws SQLException;

    public abstract boolean validate();

    /**
     * Menambahkan pesan error pada atribut tertentu
     * @param attribute Nama atribut.
     * @param error Pesan erorr.
     */
    public void addError(String attribute, String error) {
        errors.put(attribute, error);
    }

    /**
     * Menambahkan pesan error global.
     * @param error Pesan erro global.
     */
    public void addErrorGlobal(String error) {
        addError("_global_", error);
    }

    /**
     * Melihat error pada atribut tertentu
     * @param attribute Nama atribut.
     * @return Pesan error.
     */
    public String getError(String attribute) {
        String error = errors.get(attribute);
        return (error == null) ? "" : error;
    }

    /**
     * @return Pesan error global.
     */
    public String getErrorGlobal() {
        return getError("_global_");
    }

    /**
     * Semua error dibersihkan.
     */
    public void removeAllError() {
        errors.clear();
    }

    public abstract void initAttributesLabel();

    public String getAttributesLabel(String attribute) {
        if (attributesLabel == null || !attributesLabel.containsKey(attribute)) {
            return attribute;
        }

        return attributesLabel.get(attribute);
    }
}
